# author: wuye

import logging
import platform
from datetime import datetime, timedelta, timezone
from logging.handlers import RotatingFileHandler

import pytz


class MyLogging:
    def __init__(self, filename):
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.INFO)
        if not self._check_shanghai_time:   # 如果时区不是中国时区，则把时间转为中国时区
            logging.Formatter.converter = self._beijing

        # fh = logging.FileHandler(filename=filename, mode="a", encoding="utf-8")
        fh = RotatingFileHandler(filename=filename, maxBytes=10 * 1024 * 1024, backupCount=5, encoding="utf-8")  # 每个日志文件10M大小, 超出大小生成5个备份文件
        fm = logging.Formatter("%(asctime)s - %(levelname)s - %(name)s: %(message)s")
        self.logger.addHandler(fh)
        fh.setFormatter(fm)

        # sh = logging.StreamHandler()  # 创建一个屏幕操作符
        # self.logger.addHandler(sh)
        # sh.setFormatter(fm)

    def _check_shanghai_time(self):
        return datetime.now().astimezone().tzinfo == timezone(timedelta(hours=8))

    def _beijing(self):
        return datetime.now(pytz.timezone("Asia/Shanghai")).timetuple()

    def get_log(self):
        return self.logger


if platform.system() == "Linux":
    log = MyLogging("/var/log/logging_demo.log")
else:
    log = MyLogging("./logging_demo.log")

logger = log.get_log()

line = 1000
while line > 0:
    logger.info("test")
    line-=1